package com.qingcheng.mq;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.qingcheng.dao.SeckillGoodsMapper;
import com.qingcheng.pojo.seckill.SeckillGoods;
import com.qingcheng.pojo.seckill.SeckillOrder;
import com.qingcheng.service.order.WeixinPayService;
import com.qingcheng.util.SeckillStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @Author:boy
 * @Date:2019/7/25
 * @description:
 * @ModifiedBy:
 */
@Component
public class OrderMessageListener implements MessageListener {
    private Logger logger = LoggerFactory.getLogger(OrderMessageListener.class);
    @Autowired
    private RedisTemplate redisTemplate;
    @Reference
    private WeixinPayService weixinPayService;
    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Override
    public void onMessage(Message message) {
        try {
            String content = new String(message.getBody(), "utf-8");
            SeckillStatus seckillStatus = JSON.parseObject(content, SeckillStatus.class);
            if (seckillStatus != null) {
                this.rollbackOrder(seckillStatus);
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("消息编码异常", e);
        } catch (Exception e) {
            logger.error("订单回滚失败", e);
        }
    }

    /**
     * 订单回滚操作
     *
     * @param seckillStatus
     * @throws Exception
     */
    public void rollbackOrder(SeckillStatus seckillStatus) throws Exception {
        String username = seckillStatus.getUsername();
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.boundHashOps("SeckillOrder").get(username);
        if (seckillOrder != null) {
            //关闭支付
            Map<String, String> closePay = weixinPayService.closePay(seckillStatus.getOrderId());
            if (closePay.get("return_code").equalsIgnoreCase("success") && closePay.get("result_code").equalsIgnoreCase("success")) {
                //支付关闭成功 删除订单
                redisTemplate.boundHashOps("SeckillOrder").delete(username);
                //回滚库存
                SeckillGoods seckillGoods = (SeckillGoods) redisTemplate.boundHashOps("SeckillGoods_" + seckillStatus.getTime()).get(seckillStatus.getGoodsId());
                //redis中没有，从数据库中加载
                if (seckillGoods == null) {
                    seckillGoods = seckillGoodsMapper.selectByPrimaryKey(seckillStatus.getGoodsId());
                }
                //数量加一
                Long count = redisTemplate.boundHashOps("SekillGoodsCount").increment(seckillStatus.getGoodsId(), 1l);
                seckillGoods.setStockCount(1);
                //商品添加到缓存中
                redisTemplate.boundHashOps("SeckillGoods_" + seckillStatus.getTime()).put(seckillStatus.getGoodsId(), seckillGoods);
                //库存队列加1
                redisTemplate.boundListOps("SeckillGoodsCountList_" + seckillStatus.getGoodsId()).leftPush(seckillStatus.getGoodsId());
                //清理排队标识
                redisTemplate.boundHashOps("UserQueueCount").delete(username);
                //清理抢单标识
                redisTemplate.boundHashOps("UserQueueStatus").delete(username);
            }
        }
    }
}
